import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import axios from '../../api'; // 你的 axios 实例

export default function AuthWrapper({ children }) {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const checkAuth = async () => {
      const accessToken = localStorage.getItem('access_token');
      const refreshToken = localStorage.getItem('refresh_token');

      if (!accessToken && !refreshToken) {
        // 都没有 token，直接去登录页
        navigate('/login', { replace: true });
        return;
      }

      try {
        if (accessToken) {
          // 尝试用 access_token 请求 profile 接口，验证有效性
          await axios.get('/user/profile', {
            headers: { Authorization: accessToken }
          });
        } else if (refreshToken) {
          // access_token 不存在或无效，尝试刷新
          const res = await axios.post('/user/refresh', { refresh_token: refreshToken });
          localStorage.setItem('access_token', res.access_token);
          localStorage.setItem('refresh_token', res.refresh_token);
        }
      } catch (err) {
        // 刷新失败或者 access_token 无效
        localStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
        localStorage.removeItem('user');
        navigate('/login', { replace: true });
        return;
      }

      setLoading(false);
    };

    checkAuth();
  }, [navigate]);

  if (loading) return null; // 可以替换成加载中动画
  return children;
}
